﻿/*
Copyright 2011 Shane Ng

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using freemarker.template;
using Freemarker.Net.Directive;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.IO;

namespace Freemarker.Net.MvcViewEngine {
    public class FreemarkerViewEngine : VirtualPathProviderViewEngine {
        Configuration config;
        [ImportMany]
        IEnumerable<ImportableDirective> directives;
        public FreemarkerViewEngine(string rootPath, string encoding = "utf-8") {
            config = new Configuration();
            config.setDirectoryForTemplateLoading(new java.io.File(rootPath));
            AspNetObjectWrapper wrapper = new AspNetObjectWrapper();

            PagesSection section = (PagesSection)WebConfigurationManager.OpenWebConfiguration("~/").GetSection("system.web/pages");
            if (section != null) {
                foreach (NamespaceInfo info in section.Namespaces) {
                    wrapper.AddExtensionNamespace(info.Namespace);
                }
            }
            config.setObjectWrapper(wrapper); base.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.ftl" };
            config.setDefaultEncoding(encoding);
            base.PartialViewLocationFormats = base.ViewLocationFormats;

            var dir = new DirectoryInfo(Path.Combine(rootPath, "bin"));
            var catalogs = dir.GetFiles("*.dll")
                              .Where(o => o.Name != "freemarker.dll" && !(o.Name.StartsWith("IKVM.") || o.Name.StartsWith("Freemarker.Net")))
                              .Select(o => new AssemblyCatalog(Assembly.LoadFile(o.FullName)));
            var container = new CompositionContainer(new AggregateCatalog(
                new AggregateCatalog(catalogs),
                new AssemblyCatalog(typeof(ImportableDirective).Assembly)
            ));
            container.ComposeParts(this);
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {
            return new FreemarkerView(config, partialPath, directives);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {
            return new FreemarkerView(config, viewPath, directives);
        }
    }
}
